import { useAppStore } from '@/store/modules/app';

// H5Router选项类型
export interface H5RouterOptions {
  onSuccess?: (data?: any) => void;
  onClose?: (hasChanges?: boolean) => void;
  onError?: (error?: any) => void;
}

/**
 * H5Router全局组合式hook - 与原组件保持一致
 * 通过设置store.themeConfig.navUrl来触发H5Router显示
 */
export function useH5Router() {
  const appStore = useAppStore();

  /**
   * 打开H5Router弹窗 - 与原组件保持一致
   * @param url 目标URL
   * @param options 配置选项
   */
  const open = (url: string, options: H5RouterOptions = {}) => {
    if (!url) {
      window.$message?.error('URL不能为空');
      return;
    }

    // 🔧 修复：设置navUrl，与原组件保持一致
    appStore.openH5Router(url);

    // 存储回调函数到全局状态
    if (options.onSuccess || options.onClose || options.onError) {
      (window as any).__h5RouterCallbacks = {
        onSuccess: options.onSuccess,
        onClose: options.onClose,
        onError: options.onError
      };
    }
  };

  /**
   * 关闭H5Router弹窗
   */
  const close = () => {
    appStore.closeH5Router();

    // 清理回调函数
    (window as any).__h5RouterCallbacks = {};
  };

  /**
   * 打开商品编辑页面
   * @param goodId 商品ID (objectId)
   * @param options 配置选项
   */
  const openGoodEdit = (goodId: string, options: H5RouterOptions = {}) => {
    // ✅ 正确的编辑路由格式 - 编辑和新增都用goodAdd页面，通过objectId区分
    const editUrl = `/pages/manage/good/goodAdd/goodAdd?objectId=${goodId}`;

    open(editUrl, {
      onSuccess: data => {
        window.$message?.success('商品编辑成功');
        options.onSuccess?.(data);
      },
      onClose: options.onClose,
      onError: options.onError
    });
  };

  /**
   * 打开商品详情页面
   * @param goodId 商品ID (objectId)
   * @param options 配置选项
   */
  const openGoodDetail = (goodId: string, options: H5RouterOptions = {}) => {
    // 🔧 修复：使用正确的URL路径格式
    const detailUrl = `/pages/manage/good/goodDetail/goodDetail?objectId=${goodId}`;

    open(detailUrl, options);
  };

  /**
   * 打开商品添加页面
   * @param options 配置选项
   */
  const openGoodAdd = (options: H5RouterOptions = {}) => {
    // ✅ 正确的添加路由格式 - 不需要objectId和timestamp参数
    const addUrl = `/pages/manage/good/goodAdd/goodAdd`;

    open(addUrl, {
      onSuccess: data => {
        window.$message?.success('商品添加成功');
        options.onSuccess?.(data);
      },
      onClose: options.onClose,
      onError: options.onError
    });
  };

  /**
   * 打开商品批量编辑页面
   * @param goodIds 商品ID数组 (objectId)
   * @param options 配置选项
   */
  const openGoodBatchEdit = (goodIds: string[], options: H5RouterOptions = {}) => {
    if (!goodIds || goodIds.length === 0) {
      window.$message?.error('请选择要编辑的商品');
      return;
    }

    // 参照原项目的批量编辑路由格式 - 使用逗号分隔的ID字符串
    const editUrl = `/pages/manage/good/goodBatchEdit?objectId=${goodIds.join(',')}`;

    open(editUrl, {
      onSuccess: data => {
        window.$message?.success(`成功编辑 ${goodIds.length} 个商品`);
        options.onSuccess?.(data);
      },
      onClose: options.onClose,
      onError: options.onError
    });
  };

  // ========== 商品套餐相关方法 ==========

  /**
   * 打开商品套餐编辑页面
   * @param goodZhId 商品套餐ID (objectId)
   * @param options 配置选项
   */
  const openGoodZhEdit = (goodZhId: string, options: H5RouterOptions = {}) => {
    // 使用商品套餐编辑路由格式
    const editUrl = `/pages/manage/goodZh/add?objectId=${goodZhId}`;

    open(editUrl, {
      onSuccess: data => {
        window.$message?.success('商品套餐编辑成功');
        options.onSuccess?.(data);
      },
      onClose: options.onClose,
      onError: options.onError
    });
  };


  /**
   * 打开商品套餐添加页面
   * @param options 配置选项
   */
  const openGoodZhAdd = (options: H5RouterOptions = {}) => {
    // 使用商品套餐添加路由格式
    const addUrl = `/pages/manage/goodZh/add`;

    open(addUrl, {
      onSuccess: data => {
        window.$message?.success('商品套餐添加成功');
        options.onSuccess?.(data);
      },
      onClose: options.onClose,
      onError: options.onError
    });
  };

  return {
    // 基础方法
    open,
    close,

    // 商品操作快捷方法
    openGoodEdit,
    openGoodDetail,
    openGoodAdd,
    openGoodBatchEdit,

    // 商品套餐操作快捷方法
    openGoodZhEdit,
    openGoodZhAdd,

    // 状态访问
    get state() {
      return {
        visible: appStore.h5RouterVisible,
        navUrl: appStore.themeConfig.navUrl,
        isAddSuccess: appStore.themeConfig.isAddSuccess
      };
    }
  };
}

// 全局H5Router实例，用于window.$h5Router
export const createH5RouterInstance = () => {
  const router = useH5Router();

  return {
    open: router.open,
    close: router.close,
    openGoodEdit: router.openGoodEdit,
    openGoodDetail: router.openGoodDetail,
    openGoodAdd: router.openGoodAdd,
    openGoodBatchEdit: router.openGoodBatchEdit,
    openGoodZhEdit: router.openGoodZhEdit,
    openGoodZhAdd: router.openGoodZhAdd,
    get state() {
      return router.state;
    }
  };
};

export type H5RouterInstance = ReturnType<typeof createH5RouterInstance>;
